import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:factoryside/home/page_order.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:open_file/open_file.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';

import 'api/api.dart';
import 'home/page_home.dart';
import 'home/page_mine.dart';
import 'widget/update_dialog.dart';

// ignore: must_be_immutable
class Index extends StatefulWidget {
  int currentIndex = 0;
  int initialIndex = 0;

  Index({this.currentIndex = 0, int initialIndex = 0});

  @override
  State<StatefulWidget> createState() => IndexState();
}

class IndexState extends State<Index> with AutomaticKeepAliveClientMixin {
  var bodyList = [
    HomePage(),
    OrderPage(),
//    HomePage(),
    MinePage(),
  ];

  var pageController = PageController();

  int currentIndex = 0;

  void onTap(int index) {
    pageController.jumpToPage(index);
  }

  void onPageChanged(int index) {
    setState(() {
      currentIndex = index;
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  String _platformVersion = 'Unknown';
  bool _isAipOCR = false;
  GlobalKey<UpdateDialogState> _dialogKey = new GlobalKey();

  final JPush jpush = JPush();
  bool hasUnreadMsg = false; //是否有未读消息显示红点
  double whDot = 10; //红点宽高

  PackageInfo packageInfo;

  @override
  initState() {
    super.initState();
    setState(() {
      currentIndex = widget.currentIndex;
      pageController = PageController(initialPage: currentIndex);
      bodyList = [
        HomePage(),
        OrderPage(initialIndex: widget.initialIndex),
//    HomePage(),
        MinePage(),
      ];
    });
    if (Platform.isIOS) {
      PackageInfo.fromPlatform().then((value) => this.setState(() {
            packageInfo = value;
            String appName = packageInfo.appName;
            String packageName = packageInfo.packageName;
            String version = packageInfo.version;
            String buildNumber = packageInfo.buildNumber;
            print(
                'appName:$appName,packageName:$packageName,version:$version,buildNumber:$buildNumber');
            RequestUtil.getInstance()
                .get('http://itunes.apple.com/lookup?id=1488412445')
                .then((value) {
              var updateInfo = json.decode(value.data);
              print(updateInfo);
              double appStoreVersion = double.parse(
                  updateInfo['results'][0]['version'].replaceAll('.', ''));
              if (appStoreVersion > double.parse(version.replaceAll('.', ''))) {
                showDialog(
                  barrierDismissible: false,
                  context: context,
                  builder: (_) => AlertDialog(
                      backgroundColor: Colors.transparent,
                      contentPadding: EdgeInsets.zero,
                      content: buildContent(updateInfo['results'][0])),
                );
              }
            });
          }));
    } else {
      FlutterBugly.init(
        androidAppId: "f916d84816",
        iOSAppId: "70c0eed044",
      ).then((_result) {
        setState(() {
          _platformVersion = _result.message;
          print('bugly===$_platformVersion');
        });
      });
      FlutterBugly.getUpgradeInfo().then((_upgradeInfo) {
        if (_upgradeInfo != null) {
          _showUpdateDialog(_upgradeInfo);
        }
      });
    }

    //autoCheckUpgrade为true时，可以不用调用
//     if (mounted) _checkUpgrade();

    initPlatformState();
//    initPlatformState_ocr();
  }

  Widget buildContent(json) {
    double width = MediaQuery.of(context).size.width - 48;
    double height = MediaQuery.of(context).size.height / 2;
    var btnTxt = '立即更新';
    print('版本v${json['version']}');
    print('大小${json['fileSizeBytes']}');
    return Container(
      height: height,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Stack(
            alignment: Alignment.bottomCenter,
            children: [
              Image.asset(
                'assets/tc_head.png',
//            width: double.infinity,
                height: width * 382 / 792,
                fit: BoxFit.fill,
              ),
              Positioned(
                  bottom: 15,
                  child: Text(
                    '版本：v${json['version']}    大小：${getPrintSize(int.parse(json['fileSizeBytes']))}\n更新时间：${json['currentVersionReleaseDate']}',
                    style: TextStyle(color: Colors.white, fontSize: 10),
                  ))
            ],
          ),
          Expanded(
            child: Container(
              color: Colors.white,
              child: SingleChildScrollView(
                child: Container(
                  padding: EdgeInsets.all(10),
                  color: Colors.white,
                  child: Text(
                    "更新说明：\n${json['releaseNotes']}",
                    style: TextStyle(fontSize: 12),
                  ),
                ),
              ),
            ),
          ),
          Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius:
                    BorderRadius.vertical(bottom: Radius.circular(5))),
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    child: OutlinedButton(
                      child: Text(
                        '下次再说',
                        style: TextStyle(fontSize: 12),
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    child: OutlinedButton(
                      child: Text(
                        btnTxt,
                        style: TextStyle(fontSize: 12),
                      ),
                      onPressed: () {
                        gotoAppStore();
                        Navigator.of(context).pop();
                      },
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

//   Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;

    try {
      jpush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
        print("flutter onReceiveNotification: $message");
        setState(() {
//              debugLable = "flutter onReceiveNotification: $message";
        });
        if (message['title'] == '您有新工单') {
//              playMp3();
        }
      }, onOpenNotification: (Map<String, dynamic> message) async {
        print("flutter onOpenNotification: $message");
        setState(() {
//          debugLable = "flutter onOpenNotification: $message";
        });
      }, onReceiveMessage: (Map<String, dynamic> message) async {
        print("flutter onReceiveMessage: $message");
        setState(() {
//          debugLable = "flutter onReceiveMessage: $message";
        });
      }, onReceiveNotificationAuthorization:
              (Map<String, dynamic> message) async {
        print("flutter onReceiveNotificationAuthorization: $message");
        setState(() {
//          debugLable = "flutter onReceiveNotificationAuthorization: $message";
        });
      });
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    jpush.setup(
      appKey: "8f19ec931fdccf757dec794f", //你自己应用的 AppKey
      channel: "theChannel",
      production: false,
      debug: true,
    );
    jpush.applyPushAuthority(
        NotificationSettingsIOS(sound: true, alert: true, badge: true));

    // Platform messages may fail, so we use a try/catch PlatformException.
    jpush.getRegistrationID().then((rid) {
      print("flutter get registration id : $rid");
      Api.rid = rid;
      RequestUtil.post(Api.addAndUpdatePushAccount, {
        'token': Api.rid,
        'type': '7',
        'UserID': Api.userName,
        'Platform': Platform.isIOS ? 'iOS' : 'Android',
      }).then((value) {
        print('addAndUpdatePushAccount:$value');
      });
      setState(() {
//        debugLable = "flutter getRegistrationID: $rid";
      });
    });

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
//      debugLable = platformVersion;
    });
  }
//   Platform messages are asynchronous, so we initialize in an async method.
//  Future<void> initPlatformState_ocr() async {
//    String platformVersion;
//    bool isAipOCR;
//
//    // Platform messages may fail, so we use a try/catch PlatformException.
//    try {
//      platformVersion = await FlutterAipocr.platformVersion;
//    } on PlatformException {
//      platformVersion = 'Failed to get platform version.';
//    }
//    try {
//      isAipOCR = await FlutterAipocr.init(
//          iOSAppKey: "UwG0gIryO8ldGU8nZKxzlUMG",
//          iOSSecretKey: "cSGnPUjWwR7qDKhLGaDQbFBQRvsXtNb3",
//          androidAppKey: "UwG0gIryO8ldGU8nZKxzlUMG",
//          androidSecretKey: "cSGnPUjWwR7qDKhLGaDQbFBQRvsXtNb3");
//    } on PlatformException {
//      isAipOCR = false;
//    }
//
//    // If the widget was removed from the tree while the asynchronous platform
//    // message was in flight, we want to discard the reply rather than calling
//    // setState to update our non-existent appearance.
//    if (!mounted) return;
//
//    setState(() {
//      _platformVersion = platformVersion;
//      _isAipOCR = isAipOCR;
//    });
//  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        body: PageView(
          controller: pageController,
          onPageChanged: onPageChanged,
          children: bodyList,
          physics: NeverScrollableScrollPhysics(), // 禁止滑动
        ),
//        floatingActionButton: FloatingActionButton(child: Icon(Icons.refresh),
//        onPressed: _checkUpgrade,),
        bottomNavigationBar: BottomNavigationBar(
          backgroundColor: Colors.white,
          selectedItemColor: Colors.red,
          unselectedItemColor: Colors.grey,
          showUnselectedLabels: true,
          onTap: onTap,
          currentIndex: currentIndex,
          type: BottomNavigationBarType.fixed,
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Image.asset(
                'assets/tab/home.jpg',
                width: 25,
                height: 25,
              ),
              label: '首页',
              activeIcon: Image.asset(
                'assets/tab/home_selected.jpg',
                width: 25,
                height: 25,
              ),
            ),
            BottomNavigationBarItem(
              icon: Image.asset(
                'assets/tab/order.jpg',
                width: 25,
                height: 25,
              ),
              label: '工单',
              activeIcon: Image.asset(
                'assets/tab/order_selected.jpg',
                width: 25,
                height: 25,
              ),
            ),
//            BottomNavigationBarItem(
//              icon: Stack(
//                children: [
//                  Image.asset('assets/tab/tabmsg.jpg',width: 25,height: 25,),
//                  buildRedDot()
//                ],
//                overflow: Overflow.visible,
//              ),
//              title: Text('消息'),
//              activeIcon: Stack(
//                children: [
//                  Image.asset('assets/tab/tabmsg_selected.jpg',width: 25,height: 25,),
//                  buildRedDot()
//                ],
//                overflow: Overflow.visible,
//              ),
//            ),
            BottomNavigationBarItem(
              icon: Image.asset(
                'assets/tab/mine.jpg',
                width: 25,
                height: 25,
              ),
              label: '我的',
              activeIcon: Image.asset(
                'assets/tab/mine_selected.jpg',
                width: 25,
                height: 25,
              ),
            ),
          ],
        ));
  }

  ///消息小红点
  Positioned buildRedDot() {
    return Positioned(
      top: 0,
      right: -3,
      child: Visibility(
          visible: hasUnreadMsg,
          child: Container(
              width: whDot,
              height: whDot,
              decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.all(Radius.circular(whDot / 2))),
              child: Center(
                  child: Text('',
                      style: TextStyle(color: Colors.white, fontSize: 10))))),
    );
  }

  void _showUpdateDialog(UpgradeInfo _upgradeInfo) {
    showDialog(
      barrierDismissible: _upgradeInfo.upgradeType != 2,
      context: context,
      builder: (_) => _buildDialog(_upgradeInfo),
    );
  }

  void _checkUpgrade() {
    print("获取更新中。。。");
    FlutterBugly.checkUpgrade();
  }

  Widget _buildDialog(UpgradeInfo _upgradeInfo) {
    return WillPopScope(
        onWillPop: () async => _upgradeInfo.upgradeType != 2,
        child: UpdateDialog(
          key: _dialogKey,
          upgradeInfo: _upgradeInfo,
          onClickWhenDownload: (_msg) {
            //提示不要重复下载
            showToast(_msg);
          },
          onClickWhenNotDownload: () {
            //下载apk，完成后打开apk文件，建议使用dio+open_file插件
            downloadApk(_upgradeInfo);
          },
        ));
  }

  void downloadApk(UpgradeInfo _upgradeInfo) async {
    Directory tempDir = await getExternalStorageDirectory();
    String tempPath = tempDir.path;
    String savePath = '$tempPath/update_${_upgradeInfo.versionName}.apk';
    File file = File(savePath);
    file.exists().then((value) async {
      if (value) {
        _installApk(savePath);
      } else {
        Dio dio = new Dio();
        dio.options.connectTimeout = 5000; //5s
        dio.options.receiveTimeout = 3000;
        await dio.download(_upgradeInfo.apkUrl, savePath,
            onReceiveProgress: (_received, _total) {
          _updateProgress((_received * 100) ~/ _total);
        }, options: Options(receiveTimeout: 5 * 60 * 1000)).catchError(
            (_error) {
          print(_error);
        });
        _installApk(savePath);
      }
    });
  }

  void _installApk(String path) async {
    print(path);
    print(Uri.file(path));
    OpenFile.open(path);
  }

  //dio可以监听下载进度，调用此方法
  void _updateProgress(_progress) {
    setState(() {
      print('下载进度$_progress%');
      _dialogKey.currentState.progress = _progress;
    });
  }
}
